<?php

namespace Drupal\shusy_cash_wx;

use Drupal\shusy_cash\Entity\ShusyCash;
use Drupal\shusy_cash\ShusyCashHandleInterface;
use Drupal\shusy_cash_wx\Entity\ShusyCashWx;
use Drupal\wx_transfers\WxTransfersController;

class ShusyCashWxHandler implements ShusyCashHandleInterface {

  protected $controller;

  public function __construct() {
    $this->controller = new WxTransfersController;
    return $this;
  }

  protected function getOpenId(ShusyCash $cash) {
    $account = user_load($cash->uid);
    return $account->openid;
  }

  function handler(ShusyCash $cash) {
    $e = new ShusyCashWx();
    $e->shusy_cash_id = $cash->id;
    $e->wx_transfers_id = 0;
    $e->status = 0;
    $e->save();

    $attach = "{$e->id}|shusy_cash_wx";
    $openid = $this->getOpenId($cash);
    $amount = $cash->amount;
    $desc = !empty($cash->info) ? $cash->info : '提现';

    $this->controller->toBalance('shusy_cash_wx', $attach, $openid, $amount, $desc);
  }

}
